package com.ziyucoding.springboot.labs.lab4.concurrentdemo.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Synchronized 示例1
 *
 * @author ziyucoding
 * @date 2022-10-26
 **/
@Slf4j
public class SynchronizedExample1 {
    /**
     * 同步代码块
     *
     * @param num
     * @return void
     **/
    public void sync_code_block(int num) {
        synchronized (this) {
            for (int i = 0; i < 8; i++) {
                log.info("sync_code_block {} - {}", num, i);
            }
        }
    }

    /**
     * 同步方法
     *
     * @param num
     * @return void
     **/
    public synchronized void sync_method(int num) {
        for (int i = 0; i < 8; i++) {
            log.info("sync_method {} - {}", num, i);
        }
    }

    public static void main(String[] args) {
        SynchronizedExample1 example1 = new SynchronizedExample1();
        SynchronizedExample1 example2 = new SynchronizedExample1();
        ExecutorService executorService = Executors.newCachedThreadPool();
        executorService.execute(() -> {
            example1.sync_code_block(1);
        });
        executorService.execute(() -> {
            example2.sync_code_block(2);
        });
        executorService.shutdown();
    }

}
